/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2013-2014 sagyf Yang. The Four Group.
 */

package app.models.member;

import app.Const;
import com.github.sog.annotation.TableBind;
import com.github.sog.config.StringPool;
import com.github.sog.controller.datatables.core.ColumnDef;
import com.github.sog.controller.datatables.core.DatatablesCriterias;
import com.github.sog.kit.date.DateProvider;
import com.github.sog.plugin.sqlinxml.SqlKit;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.jfinal.plugin.activerecord.*;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * .
 * </p>
 *
 * @author sagyf yang
 * @version 1.0 2014-05-16 13:08
 * @since JDK 1.6
 */
@TableBind(tableName = "ol_member_ticket_opt")
public class TicketOptRecord extends Model<TicketOptRecord> {
    /**
     * The public dao.
     */
    public static final TicketOptRecord dao = new TicketOptRecord();

    public boolean customerRecord(long member, long customer, double integral, String ticket) {
        final Date currentDate = DateProvider.DEFAULT.getCurrentDate();
        return record(member, customer, integral, 0, ticket, false, currentDate, currentDate);
    }

    public boolean custometWxRecord(long member, long customer, double integral, String ticket, long wx_ticket) {
        final Date currentDate = DateProvider.DEFAULT.getCurrentDate();
        return record(member, customer, integral, wx_ticket, ticket, true, currentDate, currentDate);
    }

    private boolean record(final long member, final long customer,
                           final double integral, final long wx_ticket,
                           final String ticket, final boolean wx,
                           final Date opt_time, final Date create_time) {
        final String reason = Const.TICKET_EXC_REASON + StringPool.COLON + "小票号：" + ticket;
        return Db.tx(new IAtom() {
            @Override
            public boolean run() throws SQLException {
                if (Member.dao.optIntegral(member, true, integral, reason)) {
                    TicketOptRecord record = new TicketOptRecord();
                    record.set(Const.MEMBER_ATTR, member);
                    record.set("customer", customer);
                    record.set("integral", integral);
                    record.set("wx_ticket", wx_ticket);
                    record.set("ticket", ticket);
                    record.set("wx", wx);
                    record.set("opt_time", opt_time);
                    record.set("create_time", create_time);
                    return record.save();

                } else {
                    return false;
                }
            }
        });

    }

    public TicketOptRecord findByTicketNo(String ticketNo) {
        return findFirst(SqlKit.sql("memberticketopt.findByTicketNo"), ticketNo);
    }

    public Page<Record> optstat(DatatablesCriterias criterias, String start, String end, String oper) {
        int pageSize = criterias.getDisplaySize();
        int pageNumber = criterias.getDisplayStart() / pageSize + 1;

        final List<ColumnDef> sortingColumnDefs = criterias.getSortingColumnDefs();

        String select = SqlKit.sql("memberticketopt.select");
        String where = SqlKit.sql("memberticketopt.where");

        List<Object> params = Lists.newArrayList();

        if (!Strings.isNullOrEmpty(start)) {
            where += " AND date_format(o.opt_time, '%Y-%m-%d') >= ?";
            params.add(start);
        }

        if (!Strings.isNullOrEmpty(end)) {
            where += " AND date_format(o.opt_time, '%Y-%m-%d') <= ?";
            params.add(end);
        }

        if (!Strings.isNullOrEmpty(oper)) {
            where += " AND (u.name like ?) OR (u.real_name like ?)";
            params.add(StringPool.PERCENT + oper + StringPool.PERCENT);
            params.add(StringPool.PERCENT + oper + StringPool.PERCENT);
        }

        String group = SqlKit.sql("memberticketopt.group");

        where += " GROUP BY o.customer, date_format(o.opt_time, '%Y-%m-%d')";

        if (sortingColumnDefs != null && !sortingColumnDefs.isEmpty()) {
            StringBuilder orderBy = new StringBuilder();
            for (ColumnDef sortingColumnDef : sortingColumnDefs)
                if (sortingColumnDef.isSortable()) {
                    orderBy.append(sortingColumnDef.getName()).append(StringPool.SPACE).append(sortingColumnDef.getSortDirection().toString());
                }
            // todo mulite column.
            final String byColumns = orderBy.toString();
            if(!Strings.isNullOrEmpty(byColumns)){
                where += " ORDER BY " + byColumns;
            }
        }
        if (!where.contains("ORDER")) {
            where += " ORDER BY optDate DESC";
        }
        if (params.isEmpty()) {
            return Db.paginate(pageNumber, pageSize, select, where);
        }
        return Db.paginate(pageNumber, pageSize, select, where, params.toArray());
    }

    public Page<Record> detailList(DatatablesCriterias criterias, String optDate, long customer, String member, String ticket) {
        String begin = optDate + " 00:00:00";
        String end = optDate + " 23:59:59";

        int pageSize = criterias.getDisplaySize();
        int pageNumber = criterias.getDisplayStart() / pageSize + 1;

        String detailSelect = SqlKit.sql("memberticketopt.detailSelect");
        String detailWhere = SqlKit.sql("memberticketopt.detailWhere");

        List<Object> params = Lists.newArrayList();
        params.add(customer);
        params.add(begin);
        params.add(end);

        if (!Strings.isNullOrEmpty(member)) {
            detailWhere += " AND (T.real_name like ? OR T.uname like ?)";
            params.add(StringPool.PERCENT + member + StringPool.PERCENT);
            params.add(StringPool.PERCENT + member + StringPool.PERCENT);
        }

        if (!Strings.isNullOrEmpty(ticket)) {
            detailWhere += " AND T.ticket = ?";
            params.add(ticket);
        }

        final List<ColumnDef> sortingColumnDefs = criterias.getSortingColumnDefs();
        if (sortingColumnDefs != null && !sortingColumnDefs.isEmpty()) {
            StringBuilder orderBy = new StringBuilder();
            for (ColumnDef sortingColumnDef : sortingColumnDefs)
                if (sortingColumnDef.isSortable()) {
                    orderBy.append(sortingColumnDef.getName()).append(StringPool.SPACE).append(sortingColumnDef.getSortDirection().toString());
                }
            // todo mulite column.
            final String byColumns = orderBy.toString();
            if(!Strings.isNullOrEmpty(byColumns)){
                detailWhere += " ORDER BY " + byColumns;
            }
        }
        if (!detailWhere.contains("ORDER")) {
            detailWhere += " ORDER BY T.opt_time DESC";
        }

        return Db.paginate(pageNumber, pageSize, detailSelect, detailWhere, params.toArray());
    }
}